package com.basic.modules.ykf.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.fastjson.TypeReference;
import com.basic.common.utils.*;
import com.basic.modules.sys.entity.SysUserEntity;
import com.basic.modules.sys.service.SysUserService;
import com.basic.modules.sys.service.impl.SysUserServiceImpl;
import com.basic.modules.ykf.model.CustomModel;
import com.basic.modules.ykf.model.CustomerConsultationRecordExcel;
import com.basic.modules.ykf.model.ExcelReq;
import com.basic.modules.ykf.model.TypeModel;
import com.basic.modules.ykf.utils.ExcelCellWidthStyleStrategy;
import com.basic.modules.ykf.utils.ExcelStyleUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.basic.modules.ykf.dao.YkfCustomerConsultDao;
import com.basic.modules.ykf.entity.YkfCustomerConsultEntity;
import com.basic.modules.ykf.service.YkfCustomerConsultService;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;


@Service("ykfCustomerConsultService")
public class YkfCustomerConsultServiceImpl extends ServiceImpl<YkfCustomerConsultDao, YkfCustomerConsultEntity> implements YkfCustomerConsultService {

    @Autowired
    private SysUserService userService;
    @Autowired
    private SysUserServiceImpl sysUserService;

    @Override
    public PageUtils queryPage(ParamsModel<YkfCustomerConsultEntity> params) {
        if (ObjectUtil.isEmpty(params.getSort()) || StrUtil.isBlank(params.getSort().getOrder()) || StrUtil.isBlank(params.getSort().getSidx())) {
            ParamsModel.SortParams sortParams = new ParamsModel.SortParams();
            sortParams.setOrder("desc");
            sortParams.setSidx("createTime");
        }
        //默认创建时间倒序排
        QueryWrapper<YkfCustomerConsultEntity> queryWrapper = ParamUtils.createQueryWrapperByDefaultSort(params);
        if (ObjectUtil.isNotEmpty(params) && ObjectUtil.isNotEmpty(params.getCondition())) {
            if (ObjectUtil.isNotEmpty(params.getCondition().getKeyword())) {
                queryWrapper.lambda().like(YkfCustomerConsultEntity::getCustomerName, params.getCondition().getKeyword());
            }
            if (ObjectUtil.isNotEmpty(params.getCondition().getCreateTimeStart())) {
                queryWrapper.lambda().ge(YkfCustomerConsultEntity::getCreateTime, params.getCondition().getCreateTimeStart());
            }
            if (ObjectUtil.isNotEmpty(params.getCondition().getCreateTimeEnd())) {
                queryWrapper.lambda().le(YkfCustomerConsultEntity::getCreateTime, params.getCondition().getCreateTimeEnd());
            }
            if (ObjectUtil.isNotEmpty(params.getCondition().getUpdateTimeStart())) {
                queryWrapper.lambda().ge(YkfCustomerConsultEntity::getUpdateTime, params.getCondition().getUpdateTimeStart());
            }
            if (ObjectUtil.isNotEmpty(params.getCondition().getUpdateTimeEnd())) {
                queryWrapper.lambda().le(YkfCustomerConsultEntity::getUpdateTime, params.getCondition().getUpdateTimeEnd());
            }
            if (StrUtil.isNotBlank(params.getCondition().getSearchStatus())) {
                if (StrUtil.equals(params.getCondition().getSearchStatus(), "1")) {
                    DateTime date = DateUtil.date();
                    DateTime start = DateUtil.beginOfDay(date);
                    DateTime end = DateUtil.endOfDay(date);
                    queryWrapper.lambda().gt(YkfCustomerConsultEntity::getCreateTime, start)
                            .lt(YkfCustomerConsultEntity::getCreateTime, end);
                } else if (StrUtil.equals(params.getCondition().getSearchStatus(), "2")) {
                    DateTime date = DateUtil.date();
                    DateTime start = DateUtil.beginOfWeek(date);
                    DateTime end = DateUtil.endOfWeek(date);
                    queryWrapper.lambda().gt(YkfCustomerConsultEntity::getCreateTime, start)
                            .lt(YkfCustomerConsultEntity::getCreateTime, end);
                } else if (StrUtil.equals(params.getCondition().getSearchStatus(), "3")) {
                    String name = CommonUtils.getUser().getName();
                    queryWrapper.lambda().eq(YkfCustomerConsultEntity::getMasterName, name);
                } else if (StrUtil.equals(params.getCondition().getSearchStatus(), "4")) {
                    Long userId = CommonUtils.getUserId();
                    queryWrapper.lambda().like(YkfCustomerConsultEntity::getFavoriteUser, StrUtil.toString(userId));
                }
            }
        }
        //过滤数据权限
//        List<Long> powerUserIds = userService.getPowerUIds();
//        List<Long> powerUserIds = userService.getPowerUserIds();
//        if (ObjectUtil.isNotEmpty(powerUserIds)) {
//            queryWrapper.lambda().in(YkfCustomerConsultEntity::getCreateUserId, powerUserIds);
//        }
        //过滤只看自己的权限
        if (sysUserService.getOneselfFlag()) {
            queryWrapper.lambda().eq(YkfCustomerConsultEntity::getCreateUserId, CommonUtils.getUserId());
        }
        IPage<YkfCustomerConsultEntity> page = this.page(
                new Query<YkfCustomerConsultEntity>().getPage(BeanUtil.beanToMap(params.getPage())),
                queryWrapper
        );
        if (ObjectUtil.isNotEmpty(page) && ObjectUtil.isNotEmpty(page.getRecords())) {
            Long userId = CommonUtils.getUserId();
            for (YkfCustomerConsultEntity record : page.getRecords()) {
                if (ObjectUtil.isNotEmpty(record.getCreateUserId())) {
                    SysUserEntity user = userService.getById(record.getCreateUserId());
                    record.setCreateUserName(user.getName());
                }
                record.setFavoriteStatus(0);
                if (StrUtil.isNotBlank(record.getFavoriteUser())) {
                    List<String> split = StrUtil.split(record.getFavoriteUser(), ',');
                    if (split.contains(StrUtil.toString(userId))) {
                        record.setFavoriteStatus(1);
                    }
                }
            }
        }
        return new PageUtils(page);
    }

//    public List<YkfCustomerConsultEntity> queryList() {
//        List<YkfCustomerConsultEntity> list = this.list();
//        if (ObjectUtil.isNotEmpty(list)) {
//            Long userId = CommonUtils.getUserId();
//            for (YkfCustomerConsultEntity record : list) {
//                if (ObjectUtil.isNotEmpty(record.getCreateUserId())) {
//                    SysUserEntity user = userService.getById(record.getCreateUserId());
//                    record.setCreateUserName(user.getName());
//                }
//                record.setFavoriteStatus(0);
//                if (StrUtil.isNotBlank(record.getFavoriteUser())) {
//                    List<String> split = StrUtil.split(record.getFavoriteUser(), ',');
//                    if (split.contains(StrUtil.toString(userId))) {
//                        record.setFavoriteStatus(1);
//                    }
//                }
//            }
//        }
//        return list;
//    }

    @Override
    public void customerConsultationRecord(ExcelReq req, HttpServletResponse response) throws IOException {
        //查询列表
        ParamsModel<YkfCustomerConsultEntity> params = new ParamsModel<>();
        params.setCondition(req.getCondition(new TypeReference<YkfCustomerConsultEntity>() {}));
        params.setSort(req.getSort());
        ParamsModel.PageParams pageParams = new ParamsModel.PageParams();
        pageParams.setIndex(1L);
        pageParams.setSize(9999L);
        params.setPage(pageParams);
        PageUtils pageUtils = queryPage(params);
        List<YkfCustomerConsultEntity> consultList = (List<YkfCustomerConsultEntity>) pageUtils.getList();
        List<CustomerConsultationRecordExcel> list = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(consultList)) {
            Gson gson = new Gson();
            for (YkfCustomerConsultEntity item : consultList) {
                CustomerConsultationRecordExcel excel = new CustomerConsultationRecordExcel();
                BeanUtil.copyProperties(item, excel);
                if (StrUtil.isNotBlank(item.getContactJson())) {
                    try {
                        List<TypeModel> models = gson.fromJson(item.getContactJson(), new TypeToken<List<TypeModel>>() {
                        }.getType());
                        if (ObjectUtil.isNotEmpty(models)) {
                            StringBuffer buffer = new StringBuffer();
                            for (TypeModel model : models) {
//                                buffer.append(model.getType()).append("/").append(model.getNo()).append("\n");
                                switch (model.getType()) {
                                    case "电话":
                                        excel.setPhone(model.getNo());
                                        break;
                                    case "微信":
                                        excel.setWechat(model.getNo());
                                        break;
                                    case "QQ":
                                        excel.setQq(model.getNo());
                                        break;
                                    case "千牛":
                                        excel.setQianNiu(model.getNo());
                                        break;
                                    case "抖音":
                                        excel.setDouYin(model.getNo());
                                        break;
                                    case "拼多多":
                                        excel.setPinDuoDuo(model.getNo());
                                        break;
                                    case "百度":
                                        excel.setBaidu(model.getNo());
                                        break;
                                    case "其他":
                                        excel.setOther(model.getNo());
                                        break;
                                }
                            }
                        }
                    } catch (Exception e) {
                        log.error(e.getMessage());
                    }
                }
                list.add(excel);
            }
        }
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("客户咨询记录", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                new HorizontalCellStyleStrategy(ExcelStyleUtils.getHeadStyle(), ExcelStyleUtils.getContentStyle());
        ExcelCellWidthStyleStrategy widthStyleStrategy = new ExcelCellWidthStyleStrategy();
        EasyExcel.write(response.getOutputStream(), CustomerConsultationRecordExcel.class)
                .sheet("客户咨询记录")
                .registerWriteHandler(horizontalCellStyleStrategy)
                .registerWriteHandler(widthStyleStrategy)
                .doWrite(list);
    }

}
